<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    append-to-body
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="选手" prop="playerId">
        <el-select
          v-model="form.playerId"
          placeholder="请选择选手"
          style="width: 100%"
          :disabled="form.id !== undefined"
          @change="handlePlayerChange"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视觉图片" prop="vateImages">
        <el-upload
          class="image-uploader"
          action="#"
          :http-request="uploadImage"
          :show-file-list="false"
          :before-upload="beforeImageUpload"
        >
          <img
            v-if="imagePreviewUrl"
            :src="imagePreviewUrl"
            class="uploaded-image"
          />
          <i v-else class="el-icon-plus upload-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { put, getFileNameUUID, getFileName, getFile } from "@/utils/ali-oss";

export default {
  name: "EditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    playerOptions: {
      type: Array,
      default: () => [],
    },
    data: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: {
        id: undefined,
        playerId: undefined,
        playerName: undefined,
        vateImages: "",
      },
      rules: {
        playerId: [
          { required: true, message: "选手不能为空", trigger: "change" },
        ],
        vateImages: [
          { required: true, message: "视觉图片不能为空", trigger: "change" },
        ],
      },
      imagePreviewUrl: "",
    };
  },
  watch: {
    data: {
      handler(val) {
        if (val) {
          this.form = { ...val };
        }
      },
      immediate: true,
    },
    "form.vateImages": {
      immediate: true,
      async handler(newVal) {
        if (newVal) {
          this.imagePreviewUrl = await getFile(newVal);
        } else {
          this.imagePreviewUrl = "";
        }
      },
    },
  },
  methods: {
    beforeImageUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    async uploadImage(params) {
      try {
        const fileName = getFileNameUUID() + getFileName(params.file.name);
        const result = await put(fileName, params.file);
        if (result) {
          this.form.vateImages = fileName;
          this.imagePreviewUrl = await getFile(fileName);
          this.$message.success("图片上传成功");
        } else {
          throw new Error("上传返回结果格式错误");
        }
      } catch (error) {
        console.error("图片上传失败", error);
        this.$message.error("图片上传失败：" + (error.message || "未知错误"));
      }
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$emit("submit", this.form);
        }
      });
    },
    cancel() {
      this.reset();
      this.$emit("update:visible", false);
    },
    reset() {
      this.form = {
        id: undefined,
        playerId: undefined,
        playerName: undefined,
        vateImages: "",
      };
      this.imagePreviewUrl = "";
      this.$nextTick(() => {
        this.$refs["form"]?.resetFields();
      });
    },
    handlePlayerChange(value) {
      const selectedPlayer = this.playerOptions.find(item => item.value === value);
      if (selectedPlayer) {
        this.form.playerName = selectedPlayer.label;
      }
    },
  },
};
</script>

<style scoped>
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
